package com.chart.dao.impl;

import com.chart.dao.StudentDao;
import com.chart.model.StudentEntity;
import org.hibernate.Criteria;
import org.hibernate.Query;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 学生持久层接口实现
 */
@Repository
public class StudentDaoImpl implements StudentDao {

    @Resource
    private SessionFactory sessionFactory;

    @Resource
    private HibernateTemplate hibernateTemplate;

    @Override
    public void add(StudentEntity student) {
        Session session = sessionFactory.openSession();
        session.save(student);
        session.close();
    }

    @Override
    public List<StudentEntity> getAll() {
        Session session = sessionFactory.openSession();
        Criteria criteria = session.createCriteria(StudentEntity.class);
        List<StudentEntity> list = criteria.list();
        session.close();
        return list;
    }
    @Override
    public List<StudentEntity> getListByCondition(StudentEntity student,Integer startScore,Integer endScore,Integer startTotalScore,Integer endTotalScore) {

        StringBuilder sb = new StringBuilder();
        sb.append("from StudentEntity where 1=1 ");
        if (!StringUtils.isEmpty(student.getName())) {
           sb.append(" and name ='"+student.getName()+"'");
        }
        if (!StringUtils.isEmpty(student.getSex())) {
           sb.append(" and sex ='"+student.getSex()+"'");
        }
        if (!StringUtils.isEmpty(student.getCourse())) {
           sb.append(" and course ='"+student.getCourse()+"'");
        }
        if (student.getUploadFlag()!=null) {
           sb.append(" and uploadFlag = "+student.getUploadFlag());
        }
        if (!StringUtils.isEmpty(startScore)) {
           sb.append(" and score >="+startScore);
        }
        if (!StringUtils.isEmpty(endScore)) {
           sb.append(" and score <"+endScore);
        }
        if (!StringUtils.isEmpty(startTotalScore)) {
           sb.append(" and totalScore >="+startTotalScore);
        }
        if (!StringUtils.isEmpty(endTotalScore)) {
           sb.append(" and totalScore <"+endTotalScore);
        }
        Session session = sessionFactory.openSession();
        Query  query = session.createQuery(sb.toString());

        List<StudentEntity> list = query.list();
        session.close();
        return list;
    }

    @Override
    public void updateStudent(StudentEntity student) {
        hibernateTemplate.update(student);
    }

    @Override
    public void deleteStudent(StudentEntity student) {
        hibernateTemplate.delete(student);
    }
}